package com.huikeportal.controller;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.huikeportal.controller.common.MessageManager;
import com.huikeportal.model.MenuInfo;
import com.huikeportal.model.UserInfo;
import com.huikeportal.model.common.SqlParameter;
import com.huikeportal.service.LoginService;

@Controller
@Scope("prototype")
public class LoginController {

	@Autowired
	private HttpSession session;

	@Autowired
	private LoginService loginService;

	@Autowired
	private HttpServletRequest request;

	@InitBinder("userInfo")
	public void initBinder(WebDataBinder binder) {
		binder.setFieldDefaultPrefix("userInfo.");
	}

	@RequestMapping("/pageLoad")
	public String pageLoad(ModelMap model) throws Exception {
		// 如果存在session
		if (!"".equals(session.getAttribute("sessionUserName"))
				&& session.getAttribute("sessionUserName") != null) {
			model.addAttribute("userName", session.getAttribute("realName")
					.toString());
		}
		return MessageManager.getMsg("mainPage");
	}

	@RequestMapping("/loginSub")
	public String loginSub(HttpServletResponse req, UserInfo userInfo,
			ModelMap model) throws Exception {
		String address = userInfo.getAddress();
		// 如果是没有session
		if ("".equals(session.getAttribute("sessionUserName"))
				|| session.getAttribute("sessionUserName") == null) {
			if ("".equals(address)) {
				return "redirect:/index";
			}
			if (userInfo == null || userInfo.getUserName() == null) {
				return "redirect:/" + address;
			}
			// 从session中获取验证码
			if ("".equals(session.getAttribute("validateCode"))
					|| session.getAttribute("validateCode") == null) {
				request.setAttribute("errorMsg", "验证码已过期！");
				request.setAttribute("usName", userInfo.getUserName());
				request.setAttribute("usPsd", userInfo.getPassWord());
				return "forward:/" + address;
			}
			String validateCode = session.getAttribute("validateCode")
					.toString().toUpperCase();
			if (!validateCode.equals(userInfo.getValidateCode().toUpperCase())) {
				request.setAttribute("errorMsg", "验证码不正确，请重新输入！");
				request.setAttribute("usName", userInfo.getUserName());
				request.setAttribute("usPsd", userInfo.getPassWord());
				return "forward:/" + address;
			}
			// 获取当前系统登录需要的source
			userInfo.setSource(MessageManager.getMsg("selectSource"));
			String message = loginService.loginValidate(userInfo);
			if (!"".equals(message)) {
				request.setAttribute("errorMsg", message);
				request.setAttribute("usName", userInfo.getUserName());
				return "forward:/" + address;
			}
			// 记录用户选择的系统语言
			session.setAttribute("sysLang", "zh_cn");
			// 将用户信息放入session中
			session.setAttribute("sessionUserName", userInfo);
			session.setAttribute("userName", userInfo.getUserName());
			// 如果勾选了记住用户，将用户名放入cookie中
			if ("1".equals(userInfo.getIsRemind())) {
				Cookie idCookie = new Cookie("bigdata_pcremembername", userInfo
						.getUserName());
				Cookie pswCookie = new Cookie("bigdata_pcrememberpwd", userInfo
						.getPassWord());
				idCookie.setMaxAge(30 * 24 * 3600);
				pswCookie.setMaxAge(30 * 24 * 3600);
				req.addCookie(idCookie);
				req.addCookie(pswCookie);
			}
			// 如果是不保存用户名
			else {
				Cookie idCookie = new Cookie("bigdata_pcremembername", userInfo
						.getUserName());
				Cookie pswCookie = new Cookie("bigdata_pcrememberpwd", userInfo
						.getPassWord());
				idCookie.setMaxAge(0);
				pswCookie.setMaxAge(0);
				req.addCookie(idCookie);
				req.addCookie(pswCookie);
			}
			// 获取用户真名，放入session中
			userInfo = loginService.getUserInfo(userInfo);
			userInfo.setSysLang(session.getAttribute("sysLang").toString());
			// 更新用户表(更新用户选择的语言)
			loginService.updateSysLang(userInfo);
			session.setAttribute("realName", userInfo.getRealName());
			// 获取当前用户的权限菜单页面和所有菜单页面放入session中
			// 获取当前登录用户所有的最大菜单权限
			List<MenuInfo> roleMenuList = loginService
					.getMenuPermission(userInfo);
			// 获取所有的页面菜单
			List<MenuInfo> allMenuList = loginService.getChildMenuList(userInfo
					.getSysLang());
			session.setAttribute("roleMenuList", roleMenuList);
			session.setAttribute("allMenuList", allMenuList);
//			return "redirect:" + MessageManager.getMsg("chainAddress")
//					+ "loginSub?userName=" + userInfo.getUserName();
			 return "redirect:/" + address;
		}
		UserInfo user = (UserInfo) session.getAttribute("sessionUserName");
		user = loginService.getUserInfo(user);
		// 获取用户初始化显示的第一个页面的跳转地址
		SqlParameter sqlParam = new SqlParameter();
		sqlParam.setString(user.getUserName());
		sqlParam.setStringChar(session.getAttribute("sysLang").toString());
		List<String> url = loginService.selectFirstPageUrl(sqlParam);
		 return "redirect:/" + url.get(0);
//		return "redirect:" + MessageManager.getMsg("chainAddress")
//				+ "loginSub?userName=" + user.getUserName();
	}

	@SuppressWarnings("unchecked")
	@RequestMapping("/logout")
	public String logout(HttpServletResponse req) {
		// 清除SESSION
		Enumeration e = session.getAttributeNames();
		while (e.hasMoreElements()) {
			session.removeAttribute(e.nextElement().toString());
		}
		// 清空SESSION
		this.session.invalidate();
		// // 清空cookie
		// Cookie pswCookie = new Cookie("bigdata_pcrememberpwd", "");
		// pswCookie.setMaxAge(0);
		// req.addCookie(pswCookie);
		return MessageManager.getMsg("mainPage");
	}

	@RequestMapping("/userLoginSub")
	@ResponseBody
	public Map<String, Object> userLoginSub(HttpServletResponse req,
			String userName, String psw, String validateCode, String flag)
			throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String errorMsg = "";
		if (validateCode != null && !"".equals(validateCode)) {
			// 从session中获取验证码
			if ("".equals(session.getAttribute("validateCode"))
					|| session.getAttribute("validateCode") == null) {
				errorMsg = "验证码已过期！";
				map.put("errorMsg", errorMsg);
				return map;
			}
			String yzm = session.getAttribute("validateCode").toString()
					.toUpperCase();
			if (!yzm.equals(validateCode.toUpperCase())) {
				errorMsg = "验证码不正确，请重新输入";
				map.put("errorMsg", errorMsg);
				return map;
			}
		}
		UserInfo userInfo = new UserInfo();
		userInfo.setUserName(userName);
		userInfo.setPassWord(psw);
		userInfo.setValidateCode(validateCode);
		// 获取当前系统登录需要的source
		userInfo.setSource(MessageManager.getMsg("selectSource"));
		String message = loginService.loginValidate(userInfo);
		if (!"".equals(message)) {
			errorMsg = message;
			map.put("errorMsg", errorMsg);
			return map;
		}
		// 记录用户选择的系统语言
		session.setAttribute("sysLang", "zh_cn");
		// 将用户信息放入session中
		session.setAttribute("sessionUserName", userInfo);
		session.setAttribute("userName", userInfo.getUserName());
		// 如果勾选了记住用户，将用户名放入cookie中
		if ("1".equals(flag)) {
			Cookie idCookie = new Cookie("bigdata_pcremembername", userName);
			idCookie.setMaxAge(30 * 24 * 3600);
			req.addCookie(idCookie);
		}
		// 如果是不保存用户名
		else {
			Cookie idCookie = new Cookie("bigdata_pcremembername", userInfo
					.getUserName());
			idCookie.setMaxAge(0);
			req.addCookie(idCookie);
		}
		// 获取用户真名，放入session中
		userInfo = loginService.getUserInfo(userInfo);
		userInfo.setSysLang(session.getAttribute("sysLang").toString());
		// 更新用户表(更新用户选择的语言)
		loginService.updateSysLang(userInfo);
		session.setAttribute("realName", userInfo.getRealName());
		// 获取当前用户的权限菜单页面和所有菜单页面放入session中
		// 获取当前登录用户所有的最大菜单权限
		List<MenuInfo> roleMenuList = loginService.getMenuPermission(userInfo);
		// 获取所有的页面菜单
		List<MenuInfo> allMenuList = loginService.getChildMenuList(userInfo
				.getSysLang());
		session.setAttribute("roleMenuList", roleMenuList);
		session.setAttribute("allMenuList", allMenuList);
		map.put("errorMsg", "");
		map.put("userName", userInfo.getRealName());
		return map;
	}

	@ResponseBody
	@RequestMapping("/sessionExists")
	public int sessionExists() throws Exception {
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
		if (userInfo == null) {
			return 0;
		}
		return 1;
	}
}
